package com.example.Android_test.util;

import android.os.Handler;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: anpi0413
 * Date: 23.05.13
 * Time: 11:25
 * To change this template use File | Settings | File Templates.
 */
public class IncrementSecondTimer implements Runnable {
    private Integer currentSecond = 0;
    private List<ActionListener> stepListeners = new ArrayList<ActionListener>();
    private Handler myHandler = new Handler();

    public IncrementSecondTimer() {
    }

    public void start() {
        IncrementSecondTimer customTimer = new IncrementSecondTimer();
        for (ActionListener listener : stepListeners) {
            customTimer.addStepListener(listener);
        }

        myHandler.post(customTimer);
    }

    @Override
    public void run() {
        stepFireEvent(currentSecond);

        currentSecond++;

        IncrementSecondTimer customTimer = new IncrementSecondTimer();
        for (ActionListener listener : stepListeners) {
            customTimer.addStepListener(listener);
        }

        myHandler.postDelayed(customTimer, 1000);
    }

    public void addStepListener(ActionListener listener) {
        stepListeners.add(listener);
    }

    public void removeStepListener(ActionListener listener) {
        stepListeners.remove(listener);
    }

    private void stepFireEvent(Object event) {
        for (ActionListener listener : stepListeners) {
            listener.actionPerformed(event);
        }
    }

    public interface ActionListener {
        public void actionPerformed(Object o);
    }
}
